package rock.serialize.hessian;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import rock.serialize.Serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class HessianSerializer implements Serializer {

    private final ThreadLocal<Hessian2Output> hOutPutThreadLocal = ThreadLocal.withInitial(() -> {
        Hessian2Output output = new Hessian2Output();
        return output;
    });


    private final ThreadLocal<Hessian2Input> hInPutThreadLocal = ThreadLocal.withInitial(() -> {
        Hessian2Input input = new Hessian2Input();
        return input;
    });

    @Override
    public byte[] serialize(Object obj) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //Hessian2Output output = new Hessian2Output();
        Hessian2Output output = hOutPutThreadLocal.get();
        output.writeObject(obj);
        output.flush();

        byte[] bytes = baos.toByteArray();
        baos.close();
        output.close();
        hOutPutThreadLocal.remove();
        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        //Hessian2Input input = new Hessian2Input(bais);
        Hessian2Input input = hInPutThreadLocal.get();
        Object obj = input.readObject();
        bais.close();
        input.close();
        hInPutThreadLocal.remove();
        return clazz.cast(obj);
    }
}
